package com.jing21.learn.basic.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jing21.learn.basic.mapper.UserMapper;
import com.jing21.learn.basic.mq.MqUserSource;
import com.jing21.learn.common.learn.PageQuery;
import com.jing21.learn.intf.entity.LearnUser;
import com.jing21.learn.intf.entity.Product;
import com.jing21.learn.intf.feignclients.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * Created by 郑靖 on 2017/9/15.
 */
@RestController
@RequestMapping("/user")
@EnableBinding(MqUserSource.class)
public class UserController implements UserClient {

    @Autowired
    UserMapper userMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    private MqUserSource mqUserSource;

    @Override
    public boolean save(@RequestBody LearnUser user) {

        String messageType = "insert";
        if (user.getId() == null)
            userMapper.insertUseGeneratedKeys(user);
        else {
            userMapper.updateByPrimaryKey(user);
            messageType = "update";
        }
        mqUserSource.output().send(MessageBuilder.withPayload(user).setHeader("type", messageType).build());
        return true;
    }

    @Override
    public LearnUser findByLogin(String loginname) {

        LearnUser user = userMapper.queryByUnique(loginname).stream().findAny().orElse(null);
        System.err.println("user is :" + user);
        return user;
    }

    @Override
    public PageInfo<Product> selectByPage(PageQuery<LearnUser> query) {

        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> userMapper.select(query.getQuery()));
    }

    @Override
    public LearnUser selectOne(LearnUser learnUser) {

        return userMapper.selectOne(learnUser);
    }

    @Override
    public LearnUser selectById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }


}
